<script setup lang="ts">
import type { CascaderProps } from 'ant-design-vue';

import type {
  InspectionPlanModel,
  ManualInspectInput,
  ManualInspectionItemModel,
} from '#/api/equipment/models';

import { computed, onMounted, ref } from 'vue';

import { EllipsisText, Page, useVbenModal } from '@vben/common-ui';

import {
  Button,
  Card,
  Cascader,
  List,
  ListItem,
  ListItemMeta,
  RadioButton,
  RadioGroup,
  Result,
  Space,
  Tag,
} from 'ant-design-vue';

import {
  getAllManualInspectionPlanListApi,
  getManualInspectionPlanApi,
  manualInspectApi,
} from '#/api/equipment/manualInspect';

import ManualInspectFormModal from './modules/form.vue';

type ManualInspectionInput = ManualInspectionItemModel & {
  remark?: string;
  result: string;
  value?: number;
};

const loading = ref(false);
const submitLoading = ref(false);
const done = ref(false);
const machineryOptions = ref([] as CascaderProps['options']);
const machinerySelectedIds = ref([] as number[]);
const inspectionPlan = ref({} as InspectionPlanModel);
const dataList = ref([] as ManualInspectionInput[]);

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: ManualInspectFormModal,
  destroyOnClose: true,
});

function openFormModal(item: ManualInspectionInput) {
  formModalApi.setData(item);
  formModalApi.open();
}

function onComplete(id: number, value?: number, remark?: string) {
  const item = dataList.value.find((item) => item.id === id);
  if (item) {
    item.value = value;
    item.remark = remark;
  }
}

async function onSubmit() {
  submitLoading.value = true;

  const input: ManualInspectInput = {
    planId: inspectionPlan.value.id,
    partNo: '',
    data: dataList.value.map((item) => {
      return {
        inspectionItemId: item.id,
        value: item.value,
        remark: item.remark,
        result: item.result,
      };
    }),
  };

  await manualInspectApi(input);

  setTimeout(() => {
    done.value = true;
    submitLoading.value = false;
  }, 1000);
}

async function onChange() {
  await loadData();
}

function onReset() {
  loadData();
}

function restart() {
  done.value = false;
  loadData();
}

async function loadData() {
  loading.value = true;
  dataList.value.length = 0;

  const valueList = machinerySelectedIds.value;
  if (valueList && valueList.length === 3) {
    const data = await getManualInspectionPlanApi(valueList[2]!);
    inspectionPlan.value = data;
    if (!data || !data.manualInspectionItems) {
      loading.value = false;
      return;
    }

    const { manualInspectionItems } = data;
    manualInspectionItems.forEach((item) => {
      dataList.value.push({ ...item, result: 'Normal' });
    });
  }

  loading.value = false;
}

const normalCount = computed(() => {
  return dataList.value.filter((item) => item.result === 'Normal').length;
});

const abnormalCount = computed(() => {
  return dataList.value.filter((item) => item.result === 'Abnormal').length;
});

const oosCount = computed(() => {
  return dataList.value.filter((item) => item.result === 'OOS').length;
});

onMounted(async () => {
  const planList = await getAllManualInspectionPlanListApi();
  const machineryList = planList.map((item) => item.machinery);
  const lineList = machineryList.map((item) => ({
    lineId: item.lineId,
    lineName: item.line.lineName,
  }));
  machineryOptions.value = [
    ...new Map(lineList.map((item) => [item.lineId, item])).values(),
  ].map((item) => ({
    label: item.lineName,
    value: item.lineId,
    children: machineryList
      .filter((machinery) => machinery.lineId === item.lineId)
      .map((machinery) => ({
        label: machinery.workstation.wsCode,
        value: machinery.workstationId,
        children: machineryList
          .filter(
            (machinery2) =>
              machinery2.workstationId === machinery.workstationId,
          )
          .map((machinery2) => ({
            label: machinery2.machineryName,
            value: machinery2.id,
            isLeaf: true,
          })),
      })),
  }));
});
</script>

<template>
  <Page auto-content-height>
    <Card v-if="!done" class="h-full" title="设备点检">
      <template #extra>
        <Space>
          <span>设备</span>
          <Cascader
            class="w-[420px]"
            v-model:value="machinerySelectedIds"
            :options="machineryOptions"
            @change="onChange"
            placeholder="请选择点检设备"
          />
        </Space>
      </template>
      <List :data-source="dataList" :loading="loading" item-layout="horizontal">
        <template #footer>
          <div v-if="dataList.length > 0" class="flex justify-center">
            <Space :size="36">
              <Space size="middle">
                <span>正常数：{{ normalCount }}</span>
                <span>异常数：{{ abnormalCount }}</span>
                <span>超标数：{{ oosCount }}</span>
              </Space>
              <Button @click="onReset">重置</Button>
              <Button
                type="primary"
                :disabled="dataList.length === 0"
                :loading="submitLoading"
                @click="onSubmit"
              >
                提交
              </Button>
            </Space>
          </div>
        </template>
        <template #renderItem="{ item }">
          <ListItem :key="item.id">
            <template #actions>
              <RadioGroup
                v-model:value="item.result"
                button-style="solid"
                size="large"
              >
                <RadioButton value="Normal"> --正常-- </RadioButton>
                <RadioButton value="Abnormal"> --异常-- </RadioButton>
                <RadioButton value="OOS"> --超标-- </RadioButton>
              </RadioGroup>
            </template>
            <template #extra>
              <Button type="link" @click="openFormModal(item)">
                填写信息
              </Button>
            </template>
            <ListItemMeta>
              <template #title> {{ item.subjectName }} </template>
              <template #description>
                <EllipsisText
                  :line="2"
                  :max-width="400"
                  :tooltip="false"
                  expand
                >
                  {{ item.standard }}
                </EllipsisText>
              </template>
            </ListItemMeta>
            <Space :size="20">
              <EllipsisText :line="2" :max-width="400" :tooltip="false" expand>
                {{ item.remark }}
              </EllipsisText>
              <Tag color="blue">{{ item.value }}</Tag>
            </Space>
          </ListItem>
        </template>
      </List>
    </Card>
    <Result v-if="done" status="success" title="点检数据已成功提交">
      <template #extra>
        <Button type="primary" @click="restart"> 再次点检 </Button>
      </template>
    </Result>
    <FormModal @complete="onComplete" />
  </Page>
</template>
